import React, { Component } from 'react'
import PropTypes from 'prop-types'

import './index.css'

export default class Item extends Component {
  state = {
    isHover: false
  }

  static propTypes = {
    updateTodosStatus: PropTypes.func.isRequired,
    delTodosItem: PropTypes.func.isRequired
  }

  // 高阶函数
  // 鼠标移入
  handleMouseEnter = (isHover) => {
    return () => {
      this.setState({ isHover })
    }
  }

  // 高阶函数
  // 鼠标移出
  handleMouseLeave = (isHover) => {
    return () => {
      this.setState({ isHover })
    }
  }

  // 高阶函数（函数柯里化）
  // 勾选/取消
  handleChange = (id) => {
    return (event) => {
      this.props.updateTodosStatus(id, event.target.checked)
    }
  }

  // 删除某一项
  // 注意：
  // confirm 方法这里要加 window 前缀
  handleDel = (id) => {
    if (window.confirm('确定删除吗？')) {
      this.props.delTodosItem(id)
    }
  }

  render() {
    const { id, name, isDone } = this.props
    const { isHover } = this.state
    return (
      <li
        className="item-box"
        style={{ backgroundColor: isHover ? '#ddd' : '#fff' }}
        onMouseEnter={this.handleMouseEnter(true)}
        onMouseLeave={this.handleMouseLeave(false)}
      >
        <label>
          <input
            type="checkbox"
            name={name}
            id={id}
            checked={isDone}
            onChange={this.handleChange(id)}
          />
          {name}
        </label>
        <button
          style={{ display: isHover ? 'block' : 'none' }}
          onClick={() => this.handleDel(id)}
        >
          删除
        </button>
      </li>
    )
  }
}
